﻿using System;
using System.Collections.Generic;
using System.Text;
using RuanRang.Media.Core.Internal;
using RuanRang.Media.Core.Internal.Interop;
using RuanRang.Media.Core.Io;

namespace RuanRang.Media.Core.Media
{
    /// <summary>
    /// LocationMedia class
    /// </summary>
    public sealed class LocationMedia : BaseMedia
    {
        /// <summary>
        /// LocationMedia constructor
        /// </summary>
        /// <param name="mediaInput">The media input.</param>
        public LocationMedia(MediaInput mediaInput)
            : base(mediaInput)
        {
            Location = mediaInput.Source;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LocationMedia" /> class.
        /// </summary>
        /// <param name="mediaInput">The media input.</param>
        /// <param name="mediaHandle">The media handle.</param>
        internal LocationMedia(MediaInput mediaInput, IntPtr mediaHandle)
            : base(mediaInput, mediaHandle)
        {
            Location = mediaInput.Source;
        }

        /// <summary>
        /// Retreive the specified location of the media
        /// </summary>
        public string Location { get; private set; }

        /// <summary>
        /// Gets the new media instance.
        /// </summary>
        /// <returns></returns>
        protected override IntPtr GetNewMediaInstance()
        {
            if (!string.IsNullOrEmpty(MediaInput.Source) && IntropHandleManager.LibVlcHandle != IntPtr.Zero)
            {
                return LibVlcMediaInterop.libvlc_media_new_location(IntropHandleManager.LibVlcHandle, Encoding.UTF8.GetBytes(MediaInput.Source));
            }
            return IntPtr.Zero;
        }

        /// <summary>
        /// Retrive list of sub media items.
        /// </summary>
        /// <value>
        /// The sub items.
        /// </value>
        public IList<LocationMedia> SubItems
        {
            get
            {
                var result = new List<LocationMedia>();
                var data = LibVlcMediaInterop.libvlc_media_subitems(Handle);
                if (data == IntPtr.Zero)
                {
                    return result;
                }
                var count = LibVlcMediaListInterop.libvlc_media_list_count(data);
                for (var cpt = 0; cpt < count; cpt++)
                {
                    result.Add(new LocationMedia(MediaInput, LibVlcMediaListInterop.libvlc_media_list_item_at_index(data, cpt)));
                }
                return result;
            }
        }

    }
}